package com.fenghuajueli.module_user.vip

import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerScope
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import kotlinx.coroutines.delay

@Composable
fun <T> Banner(
    modifier: Modifier = Modifier,
    data: List<T>,
    timeMillis: Long = 3000,
    pageContent: @Composable PagerScope.(entity: T) -> Unit,
) {
    val pageCount = data.size
    val startIndex = Int.MAX_VALUE / 2
    val pagerState = rememberPagerState(initialPage = startIndex, pageCount = { Int.MAX_VALUE })

    LaunchedEffect(pagerState) {
        with(pagerState) {
            snapshotFlow { currentPage }.collect {
                if (pageCount > 1) {
                    delay(timeMillis)
                    pagerState.animateScrollToPage(
                        page = pagerState.currentPage + 1,
                        animationSpec = spring(stiffness = Spring.StiffnessMedium)
                    )
                }
            }
        }
    }

    HorizontalPager(
        state = pagerState,
        modifier = modifier
            .fillMaxWidth(),
    ) { index ->
        val page = (index - startIndex).floorMod(pageCount)
        pageContent(data[page])
    }
}

fun Int.floorMod(other: Int): Int = when (other) {
    0 -> this
    else -> {
        this - floorDiv(other) * other
    }
}

